<template>
  <div class="app-container" style="padding: 15px;">
    <el-card style="padding: 3px;">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="cardHeight">
            <div>教师列表:</div>
            <el-input style="margin: 5px 0;" placeholder="查询教师姓名" v-model="filterText" />
            <el-tree ref="treeNode" :data="data" show-checkbox node-key="userId" :props="defaultProps" default-expand-all
              :filter-node-method="filterNode" @check="change">
            </el-tree>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="cardHeight" style="margin: 0 10px;position: relative;">
            <div>
              <span>管理权限设置</span>
              <span style="color: #1890ff" v-if="teacherName">-{{ teacherName }}</span>
            </div>
            <el-input style="margin: 5px 0;" placeholder="查询班级名称" v-model="filterTextBj" />
            <el-tree :data="treexxList" @check-change="handleCheckChange" ref="tree" :show-checkbox="true" node-key="key"
              :props="authProps" :filter-node-method="filterNode">
            </el-tree>
            <div v-if="teacherName" class="btn">
              <el-button type="primary" @click="submitFormAuth" v-hasPermi="['system:academy:edit']">确 定</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="cardHeight" style="margin: 0 10px;position: relative;">
            <div style="margin-bottom: 20px;">
              <span>实践课程权限设置</span>
              <span style="color: #1890ff" v-if="teacherName">-{{ teacherName }}</span>
            </div>
            <el-tree :data="categoryList" @check-change="handleCheckChangeTask" ref="treeSj" :show-checkbox="true"
              node-key="id" :props="authPropsTask">
            </el-tree>
            <div v-if="teacherName" class="btn" style="position: absolute;">
              <el-button type="primary" @click="submitFormTask" v-hasPermi="['project:auth:add']">确 定</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { listXxTree, subAuth, listUserAuth } from "@/api/system/user";
import { listPermissionTree } from "@/api/project/prold";
import { getAuthList, assignCategoryAuth, categoryAuth } from "@/api/task/index";
export default {
  name: "practiceCategory",
  data() {
    return {
      data: [],
      teacherName: '',
      filterText: '',
      filterTextBj: '',
      defaultProps: {
        children: 'sysUserList',
        label: 'name',
      },
      authList: [],

      treexxList: [],
      authProps: {
        children: "childList",
        label: "name",
        value: "key",
        key: "key",
        id: 'id'
      },
      authPropsTask: {
        label: "name",
        value: "id",
        key: "id",
        id: 'id',
        disabled: 'have'
      },
      authListSelect: [],
      userId: '',
      taskId: [],
      categoryList: [],
      form: {}
    };
  },
  watch: {
    filterText(val) {
      this.$refs.treeNode.filter(val);
    },
    filterTextBj(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    // this.getType();
    this.getList();
    this.getInit();
  },
  methods: {
    getType() {
      // assignCategory().then(response => {
      //   this.categoryList = response.rows;
      // });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleCheckChangeTask(row) {
      this.taskId = [];
      this.$refs.treeSj.getCheckedNodes().forEach((item) => {
        this.taskId.push(item.id)
      })
    },
    getList() {
      listPermissionTree().then(res => {
        this.data = res.rows;
        res.rows.forEach(v => {
          v.disabled = true;
          if (v.sysUserList.length > 0) {
            v.sysUserList.forEach(y => {
              y.name = y.nickName + "(" + y.jsNumber + ")";
            });
          }
        });
      })
    },
    change(data, e, l) {
      this.$refs.treeNode.setCheckedKeys([data.userId]);
      this.teacherName = data.name;
      this.handleAuth(data.userId);
      this.handleAuth1(data.userId)
    },
    handleCheckChange() {
      const AllcheckedNodes = this.$refs.tree.getCheckedNodes(false, true); // 利用这个方法就可以获取到子节点+父节点
      this.authList = AllcheckedNodes;
    },
    getInit() {
    },
    submitFormTask() {
      assignCategoryAuth({ userId: this.taskUserId, practiceTaskConfigIds: this.taskId }).then(res => {
        if (res.code == 200) {
          this.$message.success('分配成功')
        }
      })
    },
    handleAuth1(id) {
      this.taskUserId = id;
      this.taskId = [];
      categoryAuth({ userId: id }).then(response => {
        response.rows.forEach(row => {
          this.taskId.push(row.practiceTaskConfigId)
        })
        // 数据回显
        this.$nextTick(() => {
          this.$refs.treeSj.setCheckedKeys(this.taskId);
        });
      });
    },
    // 递归
    recursionTree(node, allowedIds) {
      if (Array.isArray(node)) {
        node.forEach((item) => {
          if (!allowedIds.includes(item.key)) {
            this.$set(item, 'disabled', true);
          }
          // 递归处理子节点
          if (item.childList && item.childList.length > 0) {
            this.recursionTree(item.childList, allowedIds);
          }
        });
      }
    },
    /** 用户权限查看 */
    handleAuth(id) {
      this.authListSelect = [];
      if (this.$refs.tree != undefined) {
        this.$refs.tree.setCheckedNodes([]);
      }
      const userId = id;
      var map = {};
      this.userId = map.userId = userId;

      getAuthList({ tbBeUserId: userId }).then(response => {
        this.categoryList = response.data;
      });

      listXxTree(map).then((response) => {
        this.treexxList = response.data;
        listUserAuth(map).then((response) => {
          this.form = response.data;
          // 数据回显
          this.$nextTick(() => {
            if (this.form.haveAuthList != '*:*:*') {
              this.recursionTree(this.treexxList, this.form.haveAuthList);
            }
            this.$refs.tree.setCheckedKeys([]);
            let check = response.data;
            check.authListSelect.forEach((i, n) => {
              let node = this.$refs.tree.getNode(i);
              if (node && node.isLeaf) {
                this.$refs.tree.setChecked(node, true);
              }
            });
          });
        });
      });
    },
    /** 提交权限 */
    submitFormAuth() {
      const fcheckedkeys = this.$refs.tree.getHalfCheckedKeys()
      var checkedKeys = this.$refs.tree.getCheckedKeys(); //暂选状态的母tab的keygetCheckedNodes
      fcheckedkeys.forEach((item) => {
        checkedKeys.push(item)
      })
      subAuth({
        userId: this.userId,
        authListSelect: checkedKeys,
        authList: this.authList
      }).then((response) => {
        this.$modal.msgSuccess("修改成功");
      });
    },
  },
};
</script>
<style scoped lang="scss">
.cardHeight {
  height: 80vh;
  overflow-y: auto;
}

.btn {
  margin-top: 10px;
  position: flex;
  bottom: 10px;
  z-index: 9999;
}

::v-deep .el-card__body {
  padding: 10px;
}
</style>
